<?php

class Series_actives extends MY_Controller{
	private $status = TRUE;
	private $token = '';
	
	function __construct(){
		parent::__construct();
		$this->load->database();
		Sys::loadLanguage($this->params['lang'],'panel');
	}

	public function _remap($method, $params){
		$res = $this->checkAccessToken();
		
		$this->load->model('user_model');
		$info = $this->user_model->getInfoUser($this->params);
		$this->params['usr_info'] = $info['user'];
		
		if($res && $this->params['usr_info']['status']==1){
			$this->load->model('user_model');
			$info = $this->user_model->getInfoUser($this->params);
			$this->params['usr_info'] = $info['user'];
			
			if($this->params['usr_info']['tipo']==='admin'){
				switch ($method) {
					case 'index':
							header('Location:'.Sys::$url_base.$this->params['lang_url'].'panel');
					break;
					//	ADMIN
					case 'admin':
							$this->admin($method,$params);
					break;
					
					case 'add_serie_active':
							$this->serie_active($method,$params);
					break;
					case 'edit_serie_active':
							$this->serie_active($method,$params);
					break;
					case 'save_serie_active':
							$this->save($method,$params);
					break;
					case 'update_serie_active':
							$this->update($method,$params);
					break;
					case 'del_serie_active':
							$this->delete($method,$params);
					break;
					default:
						show_404();
					break;
				}
			}else header('Location:'.Sys::$url_base.$this->params['lang_url'].'panel');
			
		}
		else if(isset($_COOKIE["p_goto"])){ //redireccionar a alguna url despues de logearse
			$url = $_COOKIE["p_goto"];
			setcookie('p_goto', '', time()-1200, '/');
			header("Location: ".$url);
		}else{
	    	header('Location:'.Sys::$url_base.$this->params['lang_url'].'');
		}
	}

	/**
	 * 	MUESTRA UN LISTADO DE LAS SERIES PARA PODER AGERGAR O EDITAR LA INFORMACION
	 * 	DE UNA SERIE, TEMPORADA, EPISODIO
	 * 
	 * 	@param string $method 			METODO QUE LLAMA LA FUNCION
	 * 	@param array $params			PARAMETROS QUE RECIBE, PUEDEN SER SEGMENTOS DE LA URL
	 */
	public function admin($method='', $params=''){
			
		//	TITULO DE LA SECCION
		$this->params['lang_txt_seccion'] = lang('txt_seccion_serie_active_admin');
		
		//	CARGA LOS CSS
		$this->carabiner->css('dev/style.css');
		$this->carabiner->css('dev/panel/style.css');
		$this->carabiner->css('dev/panel/films/style_admin_films.css');
		
		//	CARGA LOS JS
		$js	= array(
					array('dev/libs/jquery.js'),
					array('dev/libs/jquery.tools.min.js'),
					array('dev/panel/general.js'),
				);
		$this->carabiner->js($js);
		
		//	CARGA EL MODELO SERIES_ACTIVE_MODEL PARA OBTENER LAS SERIES ACTIVAS
		$this->load->model('series_active_model');
		$res_series = $this->series_active_model->getSerieActive();
		
		if(is_array($res_series)){
			$this->params['list'] = $res_series['series_active'];
		}

		// SI EXISTE ALGUN MENSAJE
		if (isset($params['msg_action'])){
			$this->params['class_msg']	= 'msg-ok';
			$this->params['msg_action']	= $params['msg_action'];
		}

		// INDICA EL MENU PADRE Y EL SUBMENU QUE SERAN SELECCIONADOS
		$this->params['selected_menu3']		= 'mnu-selected';
		$this->params['selected_submenu7']	= 'submnu-selected';
		
		$this->params['seo'] = array(
			'title' 		=> ''.Sys::$title_web,
			'description' 	=> ''
		);
		
		// $this->params['aside_extra'] = $this->load->view('interface/panel/films/aside_buttons', $this->params, true);
		$this->load->view('interface/header',$this->params);
		$this->load->view('interface/panel/content',$this->params);
		$this->load->view('interface/panel/series/admin_series_active',$this->params);
		$this->load->view('interface/panel/aside',$this->params);
		$this->load->view('interface/footer',$this->params);	
	}

	/**
	 * MUESTRA EL FORMULARIO PARA AGREGAR UNA SERIE ACTIVA
	 * 
	 * @param $method			Metodo que llama la funcion
	 * @param $params			Parametros del Segmento de la URL u otros
	 */
	public function serie_active($method = '', $params=''){
		
		//	CARGA LOS CSS
		$this->carabiner->css('dev/libs/superbox.css');
		$this->carabiner->css('dev/style.css');
		$this->carabiner->css('dev/panel/style.css');
		$this->carabiner->css('dev/panel/style_form.css');
		
		//	CARGA LOS JS
		$js	= array(
					array('dev/libs/jquery.js'),
					array('dev/libs/superbox.jquery.js'),
					array('dev/libs/jquery.tools.min.js'),
					array('dev/panel/general.js'),
				);
		$this->carabiner->js($js);
		
		//	VARIABLE QUE SIRVE PARA INDICAR SI EXISTE ALGUN ERROR DE VALIDACION DE LOS PARAMETROS
		$show_error = FALSE;
		
		//	SI SE AGREGA O GUARDA UNA SERIE
		if($method === 'add_serie_active' || $method === 'save_serie_active'){

			//	TITULO DE LA SECCION
			$this->params['lang_txt_seccion'] = lang('txt_seccion_serie_active_add');

			$this->params['id_season']	= '';
			$this->params['image']		= '';
			$this->params['no_order']	= '';

			// SI EXISTE ALGUN MENSAJE
			if (isset($params['msg_action'])){
				$this->params['class_msg']	= 'msg-ok';
				$this->params['msg_action']	= $params['msg_action'];
			}

			// INDICA EL MENU PADRE Y EL SUBMENU QUE SERAN SELECCIONADOS
			$this->params['selected_menu3']	= 'mnu-selected';
			$this->params['selected_submenu8']	= 'submnu-selected';

			// EN CASO DE CARGAR EL FORMULARIO SE TIENEN QUE INDICAR ESTOS PARAMETROS LOS CUALES SERAN PARTE DEL ACTION DEL FORMULARIO
			$this->params['controller'] 	= 'series_actives/';
			$this->params['method'] 		= 'save_serie_active/';
			$this->params['id']				= '';

			$this->params['seo'] = array(
				'title' 		=> ''.Sys::$title_web,
				'description' 	=> ''
			);

			//	OBTIENE LAS TEMPORADAS DE LAS SERIES EXISTENTES
			$list = $this->db->select('st.id_serie, 
									   st.id_temporada AS id_season,
									   st.no_temporada AS season, 
									   s.titulo AS title')
					 			->from('series_temporadas as st')
								->join('series as s','st.id_serie = s.id_serie','inner')
								->where('st.prox_estreno !=', '1')
								->order_by('s.titulo', 'ASC')->get();

			$this->params['list'] = $list->result_array();
		}
		//	SI SE EDITA O ACTUALIZA UNA SERIE
		else if($method === 'edit_serie_active' || $method === 'update_serie_active'){
			
			// ASIGNA EL ID DE LA SERIE ACTIVA A EDITAR
			$this->params['serie_active'] = $params[0];
			
			// OBTIENE EL TOTAL DE SERIES QUE EXISTE PARA EL ID DE LA SERIE QUE SE EDITARA
			$this->db->select('id_activa')->from('series_activas')->where('id_activa',$this->params['serie_active']);
			$total = $this->db->count_all_results();

			// SI EXISTE LA SERIE QUE SE EDITARA ENTONCES ENTRA
			if($total==1){
				
				// TITULO DE LA SECCION
				$this->params['lang_txt_seccion'] = lang('txt_seccion_serie_active_edit');
				
				$this->load->model('series_active_model');
				$list_series_active = $this->series_active_model->getSerieActive();
				
				$serie_active_info = array();
				foreach ($list_series_active['series_active'] as $itm) {
					if($itm['serie_active'] == $this->params['serie_active']){
						$serie_active_info = $itm;
						break;
					}
				}
				
				$this->params['id_season']	= $serie_active_info['id_season'];
				$this->params['image']		= $serie_active_info['image'];
				$this->params['no_order']	= $serie_active_info['no_order'];
				
				// SI EXISTE ALGUN MENSAJE
				if (isset($params['msg_action'])){
					$this->params['class_msg']	= 'msg-ok';
					$this->params['msg_action']	= $params['msg_action'];
				}
	
				// INDICA EL MENU PADRE Y EL SUBMENU QUE SERAN SELECCIONADOS
				$this->params['selected_menu3']	= 'mnu-selected';
				$this->params['selected_submenu8']	= 'submnu-selected';
	
				// EN CASO DE CARGAR EL FORMULARIO SE TIENEN QUE INDICAR ESTOS PARAMETROS LOS CUALES SERAN PARTE DEL ACTION DEL FORMULARIO
				$this->params['controller'] 	= 'series_actives/';
				$this->params['method'] 		= 'update_serie_active/';
				$this->params['id']				= $this->params['serie_active'];
	
				$this->params['seo'] = array(
					'title' 		=> ''.Sys::$title_web,
					'description' 	=> ''
				);
	
				//	OBTIENE LAS TEMPORADAS DE LAS SERIES EXISTENTES
				$list = $this->db->select('st.id_serie, 
										   st.id_temporada AS id_season,
										   st.no_temporada AS season, 
										   s.titulo AS title')
						 			->from('series_temporadas as st')
									->join('series as s','st.id_serie = s.id_serie','inner')
									->where('st.prox_estreno !=', '1')
									->order_by('s.titulo', 'ASC')->get();
	
				$this->params['list'] = $list->result_array();
			}
			else{
				$show_error = TRUE;
				$this->params['msg'] = lang('txt_serie_active_id_update_error');
				$this->params['seo'] = array(
					'title' 		=> ''.Sys::$title_web,
					'description' 	=> $this->params['msg']
				);
			}		
		}

		if($show_error){
			$this->load->view("interface/header", $this->params);
			$this->load->view("interface/errors/page_error", $this->params);
			$this->load->view("interface/panel/aside", $this->params);
			$this->load->view("interface/footer", $this->params);
		}
		else{			
			$this->params['aside_extra'] = $this->load->view('interface/panel/films/aside_buttons', $this->params, true);
			$this->load->view('interface/header',$this->params);
			$this->load->view('interface/panel/content',$this->params);
			$this->load->view('interface/panel/series/form_serie_active',$this->params);
			$this->load->view('interface/panel/aside',$this->params);
			$this->load->view('interface/footer',$this->params);
		}
	}	
	
	/**
	 *	GUARDA LA INFORMACION ENVIADA DEL FORMULARIO DE LA SERIE ACTIVA
	 * 
	 * 	@param string $method			METODO QUE LLAMA LA FUNCION
	 * @param array $params				Parametros del Segmento de la URL u otros
	 */
	public function save($method, $params=''){
		
		// VALIDA LOS PARAMETROS DEPENDIENDO QUE SE GUARDARA
		$response_errors = $this->validate('active_add');
		
		// INDICA SI EXISTE ALGUN ERROR
		$show_error = FALSE;
		
		// SI NO EXISTE ERRORES EN LOS PARAMETROS VALIDADOS
		if($this->status == TRUE){
			
			// CARGA EL MODEL SERIE_ACTIVE_MODEL PARA GUARDAR LA SERIE ACTIVA
			$this->load->model('series_active_model');
			$serie = $this->series_active_model->saveInfoSerieActive($this->params);
			if(is_array($serie))
				$this->serie_active('save_serie_active',array('msg_action'=>lang('txt_serie_active_save_ok')));
			else{
				$show_error = TRUE;
				$this->params['msg'] = 'Ya existe una serie activa para la temporada seleccionada';
				$this->params['seo'] = array(
					'title' 		=> ''.Sys::$title_web,
					'description' 	=> $this->params['msg']
				);
			}
				
		}else{
			// SI EXISTEN ERRORES DE VALIDACION DE LOS PARAMETROS
			$show_error = TRUE;
			$this->params['msg'] = implode(',', $response_errors);
			$this->params['seo'] = array(
				'title' 		=> ''.Sys::$title_web,
				'description' 	=> $this->params['msg']
			);
		}
		
		// SI EXISTE UN ERROR LO MUESTRA
		if($show_error){
			$this->carabiner->css('dev/style.css');
			$this->carabiner->css('dev/panel/style.css');
			
			$js	= array(
						array('dev/libs/jquery.js'),
						array('dev/libs/jquery.tools.min.js'),
						array('dev/panel/general.js')
					);
					
			$this->carabiner->js($js);
					
			$this->load->view("interface/header", $this->params);
			$this->load->view("interface/errors/page_error", $this->params);
			$this->load->view("interface/panel/aside", $this->params);
			$this->load->view("interface/footer", $this->params);
		}
	}

	/**
	 *	ACTUALIZA LA INFORMACION DE UNA SERIE ACTIVA
	 * 
	 * 	@param string $method			METODO QUE LLAMA LA FUNCION
	 * 	@param array $params			Parametros del Segmento de la URL u otros
	 */
	public function update($method='', $params=''){
		$this->params['serie_active'] = $params[0];
		
		// VALIDA LOS PARAMETROS DE LA SERIE ACTIVA
		$response_errors = $this->validate('active_update');
		
		// SI NO EXISTEN ERRORES DE VALIDACION
		if($this->status == TRUE){
			// CARGA EL MODELO SERIES_ACTIVE_MODEL PARA ACTUALIZAR LA SERIE ACTIVA
			$this->load->model('series_active_model');
			$serie = $this->series_active_model->updateInfoSerieActive($this->params);
			if(is_array($serie))
				$this->serie_active('update_serie_active',array($this->params['serie_active'],'msg_action'=>lang('txt_serie_active_update_ok')));
		}else{
			// SI EXISTE ERRORES DE VALIDACION DE PARAMETROS
			$this->carabiner->css('dev/style.css');
			$this->carabiner->css('dev/panel/style.css');
			
			$js	= array(
						array('dev/libs/jquery.js'),
						array('dev/libs/jquery.tools.min.js'),
						array('dev/panel/general.js')
					);
			
			$this->carabiner->js($js);
			$this->params['msg'] = implode(',', $response_errors);
			$this->params['seo'] = array(
				'title' 		=> ''.Sys::$title_web,
				'description' 	=> $this->params['msg']
			);
			
			$this->load->view("interface/header", $this->params);
			$this->load->view("interface/errors/page_error", $this->params);
			$this->load->view("interface/panel/aside", $this->params);
			$this->load->view("interface/footer", $this->params);
		}
	}
	
	/**
	 *	ELIMINAR UNA SERIE ACTIVA
	 * 
	 * 	@param string $method			METODO QUE LLAMA LA FUNCION
	 * 	@param array $params			Parametros del Segmento de la URL u otros
	 */
	public function delete($method='', $params=''){
		$this->params['serie_active'] = $params[0];
		$this->validate('active_delete');
		
		$show_error = FALSE;
		if($this->status){
			$this->load->model('series_active_model');
			$serie = $this->series_active_model->deleteSerieActive($this->params);
			
			if (is_array($serie)) {
				$this->admin('', array('msg_action' => lang('txt_serie_active_delete_ok')));
			}
			else{
				$show_error = TRUE;
				$this->params['msg'] = 'No existe la serie activa que desea eliminar';
				$this->params['seo'] = array(
					'title' 		=> ''.Sys::$title_web,
					'description' 	=> ''
				);
			}
		}
		else{
			// SI EXISTE ERRORES DE VALIDACION DE PARAMETROS
			$show_error = TRUE;
			$this->params['msg'] = implode(',', $response_errors);
			$this->params['seo'] = array(
				'title' 		=> ''.Sys::$title_web,
				'description' 	=> $this->params['msg']
			);
		}
		
		if($show_error){
			$this->carabiner->css('dev/style.css');
			$this->carabiner->css('dev/panel/style.css');
			
			$js	= array(
						array('dev/libs/jquery.js'),
						array('dev/libs/jquery.tools.min.js'),
						array('dev/panel/general.js')
					);
			$this->carabiner->js($js);
			
			$this->load->view("interface/header", $this->params);
			$this->load->view("interface/errors/page_error", $this->params);
			$this->load->view("interface/panel/aside", $this->params);
			$this->load->view("interface/footer", $this->params);
		}
	}
	
	
	/**
     * Permite incorporar las validaciones bases que apliquen para todos los servicios.
     * Validaciones mas espesificas tendran que ser en cada servicio en particular.
     * @author gama
     */
    protected function validate($val_method){
    	if(method_exists($this, 'validate_'.$val_method)){
    		$this->load->library('MY_Form_validation');
    		return $this->{'validate_'.$val_method}();
    	}
    }
	
	private function validate_active_add(){
		
		$validate 	= new MY_Form_validation();
		$validate->setArrayValidate($this->params);
		
		$image_validate = array();
		
		if(!isset($_FILES['image']) && !isset($this->params['image'])){
			$image_validate = array(
					'field'	=> 'image',
					'label'	=> 'image',
					'rules'	=> 'required'
			);
		}
		else if(isset($_FILES['image']) && isset($this->params['image'])){
			if(empty($_FILES['image']['name']) && empty($this->params['image']))
				$image_validate = array(
					'field'	=> 'image',
					'label'	=> 'image',
					'rules'	=> 'required'
				);
		}
		else if(isset($_FILES['image']) && !isset($this->params['image'])){
			if(empty($_FILES['image']['name']))
				$image_validate = array(
					'field'	=> 'image',
					'label'	=> 'image',
					'rules'	=> 'required'
				);	
		} 
		else if(!isset($_FILES['image']) && isset($this->params['image'])){
			if(empty($this->params['image']))
				$image_validate = array(
					'field'	=> 'image',
					'label'	=> 'image',
					'rules'	=> 'required'
				);	
		}
		
		$config = array(
							array(
									'field'	=> 'season',
									'label'	=> 'season',
									'rules'	=> 'required|is_natural_no_zero'
							),
							$image_validate,
							array(
									'field'	=> 'no_order',
									'label'	=> 'no_order',
									'rules'	=> 'required|is_natural_no_zero'
							)
		
				);
				
		$validate->set_rules($config);
		$this->status = $validate->run();
		
		//	VALIDA QUE LA URL DEL $PARAMS['IMAGE'] SEA VALIDA.
		if(isset($this->params["image"]) && !empty($this->params["image"])){
			$url = $this->params['image'];
			if(!sys::urlValid($url)){
    			$this->status = FALSE;
    			$validate->_error_array['values'] = lang('txt_invalid_url', 'image => "'.$url.'"');
			}
    	}
		
		return $validate->_error_array;
	}

	private function validate_active_update(){
		
		$validate 	= new MY_Form_validation();
		$validate->setArrayValidate($this->params);

		$config = array(
							array(
									'field'	=> 'serie_active',
									'label'	=> 'serie_active',
									'rules'	=> 'required|is_natural_no_zero'
							),
							array(
									'field'	=> 'season',
									'label'	=> 'season',
									'rules'	=> 'required|is_natural_no_zero'
							),
							array(
									'field'	=> 'no_order',
									'label'	=> 'no_order',
									'rules'	=> 'required|is_natural_no_zero'
							)
				);
				
		$validate->set_rules($config);
		$this->status = $validate->run();
		
		//	VALIDA QUE LA URL DEL $PARAMS['IMAGE'] SEA VALIDA.
		if(isset($this->params["image"]) && !empty($this->params["image"])){
			$url = $this->params['image'];
			if(!sys::urlValid($url)){
    			$this->status = FALSE;
    			$validate->_error_array['values'] = lang('txt_invalid_url', 'image => "'.$url.'"');
			}
    	}
		
		return $validate->_error_array;
	}
	
	private function validate_active_delete(){
		$validate	= new MY_Form_validation();
		$validate->setArrayValidate($this->params);
		
		$config = array(
							array(
									'field' => 'serie_active',
									'label'	=> 'serie_active',
									'rules'	=> 'required|is_natural_no_zero'
							)
				);
		
		$validate->set_rules($config);
		$this->status = $validate->run();
		
		return $validate->_error_array;
	}
	
}